package models

import (
	"earth/config"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

var db *gorm.DB
var err error

func Init(conf config.Database) {
	host := conf.Server
	user := conf.Username
	password := conf.Password
	dbname := conf.DBname
	DbUri := user + ":" + password + "@" + host + "/" + dbname + "?charset=utf8&parseTime=True&loc=Local"
	fmt.Println(DbUri)
	db, err = gorm.Open("mysql", DbUri)
	db.DB().SetMaxIdleConns(100)
	if err != nil {
		fmt.Println(err)
	}
	db.CreateTable(&User{}, &Policy{})
	db.AutoMigrate(&User{}, &Policy{})
	defer db.Close()
}

func GetDB() *gorm.DB {
	return db
}
